package ink.lovejinhu.sync;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jinhu
 * created 2021-07-20 17:39
 */
public class ThreadCommunication {
    /**
     * 线程通信
     *
     * @param args
     */
    public static void main(String[] args) {
        Share share = new Share(10, 20);
        new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                share.consume();
            }


        }, "consume01").start();
        new Thread(() -> {

            for (int i = 0; i < 20; i++) {
                share.consume();
            }


        }, "consume02").start();
        new Thread(() -> {

            for (int i = 0; i < 30; i++) {
                share.produce();
            }


        }, "produce01").start();
    }
}

class Share {
    private int number;   //现在仓库的数量
    private int capcity;   //仓库最大的容量
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public Share(int number, int capcity) {
        this.number = number;
        this.capcity = capcity;
    }

    public void produce() {
        try {
            lock.lock();
            while (number > capcity) {  //如果现在数量大于了最大容量
                this.condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "生产了一个，number的数量是:" + number);
            this.condition.signalAll();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }

    }

    public void consume() {
        lock.lock();
        try {
            while (number <= 0) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "消费了一个，number的数量是:" + number);
            condition.signalAll();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }


    }
}
